﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NAnt.Core;
using NAnt.Core.Attributes;
using NAnt.Core.Types;
using Amazon.S3;

namespace NAntExt.Aws.Tasks
{
    /// <summary>
    /// Lists the buckets for your S3 account.
    /// </summary>
    [TaskName(S3BucketListTask.TaskName)]
    public class S3BucketListTask : AwsTaskBase
    {
        /// <summary>
        /// The name of this task.
        /// </summary>
        public const string TaskName = "s3-bucket-list";
                
        /// <summary>
        /// Primary entry point for this task.
        /// </summary>
        protected override void ExecuteTask()
        {
            try
            {
                using (var client = new Amazon.S3.AmazonS3Client(AccessKeyId, SecretAccessKey))
                {
                    using (var listBucketsResponse = client.ListBuckets())
                    {
                        foreach (var bucket in listBucketsResponse.Buckets)
                        {
                            Log(Level.Info, "Bucket {0} created on {1}.", bucket.BucketName, bucket.CreationDate);
                        }
                    }                    
                }
            }
            catch (Exception ex)
            {
#if DEBUG
                System.Diagnostics.Debug.WriteLine(ex, "Error");
#endif

                if (this.FailOnError)
                    throw new BuildException(string.Format("{0} task failed during execution due to an unhandled exception.", TaskName), this.Location, ex);
                else
                    Log(Level.Error, "{0} task failed during execution due to an unhanled exception. ex = {0}", TaskName, ex);
            }
        }

    }
}
